package com.heimali.happyreader.db;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.heimali.happyreader.HappyReaderApplication;

public class DBHelper extends SQLiteOpenHelper{

	public static final String TAG = "DBHelper";
	private final static int DATABASE_VERSION = 1;
	private static DBHelper dbHelper = null;
	private static SQLiteDatabase database = null;
	public static Object writeLock = new Object();
	
	private static String getDBName() {
		return "happy_reader.db";
	}
	
	public DBHelper(Context context) {
		super(context, getDBName(), null, DATABASE_VERSION);
	}
	
	public static DBHelper getHelper() {
		if (dbHelper == null) {
			dbHelper = new DBHelper(HappyReaderApplication.getContext());
		}
		return dbHelper;
	}
	
	public static SQLiteDatabase getDatabase() {
		if (database == null) {
			database = getHelper().getWritableDatabase();
		}
		return database;
	}
	
	/**
	 * 退出登录时执行
	 */
	public static void logout() {
		synchronized (writeLock) {
			if (dbHelper != null) {
				dbHelper.close();
				dbHelper = null;
			}
			if (database != null) {
				database.close();
				database = null;
			}
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String listTableSql = "create table if not exists list (_id integer primary key autoincrement, articleID integer, articleTime varchar(20), title varchar(255), intro varchar(255), ext1 text, ext2 text, isDownload integer default 0, isFav integer default 0, uid integer default 0);create index `articleID` on list (`articleID`);";
		db.execSQL(listTableSql);
		String articleTableSql = "create table if not exists article (_id integer primary key autoincrement, articleID integer, title varchar(255), content text, sourceUrl text, time varchar(20), ext1 text, ext2 text, uid integer default 0);create index `articleID` on list (`articleID`);";
		db.execSQL(articleTableSql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
}
